﻿using MediatR;
using RedDragon.Common.Domain.Approves;
using RedDragon.Common.Domain.warehouse;
using RedDragon.Common.Infrastructure.Interface;
using RedDragon.ERP.ErroCodeEnum;
using SqlSugar;
using System.Collections.Generic;
using T.Common.Domain.Common;

namespace RedDragon.ERP.API.Application.Commands.Inventory
{
    public class ProcessFlowEngineHandler : IRequestHandler<ProcessFlowEngineCommand, Result>
    {
        /// <summary>``
        /// 审批流程表仓储
        /// </summary>
        private readonly IBaseRepository<ApprovalProcess> approvalProcessRepository;
        /// <summary>
        /// 审批流程设置表仓储
        /// </summary>
        private readonly IBaseRepository<ProcessFlow> processFlowRepository;
        private readonly ISqlSugarClient sqlSugarClient;
        /// <summary>
        /// 日志
        /// </summary>
        private readonly ILogger<ProcessFlowEngineHandler> logger;

        public ProcessFlowEngineHandler(IBaseRepository<ApprovalProcess> approvalProcessRepository, IBaseRepository<ProcessFlow> processFlowRepository, ISqlSugarClient sqlSugarClient,ILogger<ProcessFlowEngineHandler> logger)
        {
            this.approvalProcessRepository = approvalProcessRepository;
            this.processFlowRepository = processFlowRepository;
            this.sqlSugarClient = sqlSugarClient;
            this.logger = logger;
        }
        /// <summary>
        /// 审批
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<Result> Handle(ProcessFlowEngineCommand request, CancellationToken cancellationToken)
        {
            var result = new Result() { Code = (int)CommonErrorCode.Added };
            var Emety = new ProcessFlow();
            var str = await (await processFlowRepository.GetAll()).ToListAsync();

            var processFlow = str.Where(d => d.Workid == request.Workid).FirstOrDefault();

            if (processFlow == null)
            {
                result.Msg = "未找到工作流程数据";
                return result;
            }

            var newdate = processFlow.ExamineNameList.Split(',');
            var res = "";

            foreach (var item in newdate)
            {
                if (item == request.USerid.ToString() && request.WorkType == 1)
                {
                    result.Msg = "审核通过";
                    break;
                }
                else if (request.WorkType == 0)
                {
                    result.Msg = "审核不通过";
                    break;
                }

                if (request.USerid != 1)
                {
                    var firstOrdate = await sqlSugarClient.Queryable<ApprovalProcess>()
                                        .FirstAsync(x => x.Sequence == (request.USerid - 1) && x.Typetable == request.Gnumid, cancellationToken);

                    if (firstOrdate.SeqeResult == "审核通过")
                    {
                        if (request.WorkType == 1)
                        {
                            result.Msg = "审核通过";
                            break;
                        }
                        else
                        {
                            result.Msg = "审核失败";
                            break;
                        }

                    }
                    else
                    {
                        result.Msg = "不能跨级批准请联系上一级审批人";
                        break;
                    }
                }
            }

            if (result.Data != "")
            {
                var SeqeMEssage = "";
                if (result.Msg == "审核通过")
                {
                    SeqeMEssage = "同意";
                }
                else {
                    SeqeMEssage = "不同意";
                }
                var add = new ApprovalProcess()
                {
                    ApplyId = processFlow.Workid,
                    ApplyName = request.USerid,
                    Sequence = request.USerid,
                    SeqeTime = DateTime.Now,
                    SeqeResult = result.Msg,
                    // SeqeMEssage 被设置为空字符串，但后续没有使用，可能需要确认是否需要这个字段
                    SeqeMEssage = "",
                    Typetable = request.Gnumid,
                };

                // 注意：这里应该使用 SqlSugar 的插入方法，而不是拼接 SQL 字符串
                var success = await sqlSugarClient.Insertable(add).ExecuteCommandAsync(cancellationToken);

                if (success > 0)
                {
                    result.Msg = "审批通过";
                }
                else
                {
                    // 处理插入失败的情况
                    result.Msg = "审批记录插入失败";
                }
            }

            return result;
        }
    }
}
